# -*- coding:utf-8 -*-
"""
该脚本为服务插件管理脚本
作用：
    1.实时检测服务器上所有插件版本
    2.接受客户端请求，返回插件信息

"""

import os
import yaml
import json
import socket


def get_plugins():
    config_path = os.path.join(os.path.dirname(__file__),'plugin_config.yaml')
    stream = open(config_path,mode='r',encoding='utf8')
    data = yaml.load(stream,Loader=yaml.FullLoader)
    stream.close()

    extended_info = {}
    if data:

        for plugin,info in data.items():
            # plugin_name = plugin
            # info['plugin_name'] = plugin_name
            server_path = info['server_path']
            version_list = sorted(os.listdir(server_path))
            version_data = {}
            for version in version_list:
                version_dir = os.path.join(server_path,version)
                version_txt = os.path.join(version_dir,'version.txt')
                version_info = {}
                with open(version_txt,'r',encoding='utf8') as r:
                    version_info = eval(r.read())
                version_data[version] = version_info
            info['version_data'] = version_data
            extended_info[plugin] = info
            # extended_info.update(version_data)

    return extended_info



class SoftServer(object):

    def __init__(self,HOST,PORT,BUFFER):
        super(SoftServer, self).__init__()
        self.HOST = HOST
        self.PORT = PORT
        self.BUFFER = BUFFER

    def get_plugins(self):
        dir_path = os.path.dirname(__file__)
        config_path = os.path.join(dir_path, 'plugin_config.yaml')
        stream = open(config_path, mode='r', encoding='utf8')
        data = yaml.load(stream, Loader=yaml.FullLoader)
        stream.close()

        extended_info = {}
        if data:
            for plugin, info in data.items():
                server_path = info['server_path']
                plugin_path = os.path.join(dir_path,server_path)
                version_list = sorted(os.listdir(plugin_path))
                version_data = {}
                # print(version_list)
                for version in version_list:
                    if not version.startswith('.'):  #去掉隐藏文件
                        version_dir = os.path.join(plugin_path, version)
                        version_txt = os.path.join(version_dir, 'version.txt')
                        version_info = {}
                        with open(version_txt, 'r', encoding='utf8') as r:
                            version_info = eval(r.read())
                        version_data[version] = version_info
                info['version_data'] = version_data
                extended_info[plugin] = info
        # print('extended_info:',extended_info)
        return extended_info

    def runServer(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((self.HOST, self.PORT))
        sock.listen(150)

        while True:
            try:
                client_sock,client_addr = sock.accept()
                recv = client_sock.recv(self.BUFFER)
                if recv:
                    print('接收到请求')
                    data = eval(recv.decode())
                    print(data)
                    if data['ask_type'] == 'plugin':
                        print('检测插件版本')
                        plugin_info = self.get_plugins()
                        client_sock.send(str(plugin_info).encode())
                        # client_sock.send(json.dumps(plugin_info))

            except Exception as ERR:
                print(str(ERR))


if __name__ == '__main__':
    dir_path = os.path.dirname(__file__)
    server_config_path = os.path.join(dir_path, 'server_config.yaml')
    stream = open(server_config_path, mode='r', encoding='utf8')
    data = yaml.load(stream, Loader=yaml.FullLoader)
    stream.close()
    if data:
        server_config = data['SERVER_INFO']
        HOST = server_config.get('HOST','192.168.1.222') #'192.168.1.178'
        PORT = server_config.get('PORT',6666)
        BUFFER = server_config.get('BUFFER',1024)
        # print(HOST,PORT,BUFFER)
        ss = SoftServer(HOST,PORT,BUFFER)
        ss.runServer()